<?php

/*
----------------------------------------------------------------------------
SharePoint PowerShell Automation
----------------------------------------------------------------------------
Allows the running of PowerShell Scripts Using Remoting via a Web Interface
----------------------------------------------------------------------------
*/

function checkAuthorizedUsers() {
   $server = $_SERVER['SERVER_NAME'];
   $username = strtolower($_SERVER['AUTH_USER']);
   
   $authUsers = array('terrill\rayt');
   
   if (in_array($username, $authUsers)) {
      echo "<div id=authInfo style='background-color: yellow; border: 1px solid; padding: 3px;'>You're currently logged on as [$username] on [$server]</div><br />";
   } else {
      header('HTTP/1.0 403 Forbidden');
      die("You are not allowed to access this application, [$username]");
   }
}

function displayHeader() {
   echo "<html>";
   echo "<head>";
   echo "<title>PowerShell Automation</title>";
   echo "<link rel='stylesheet' type='text/css' href='css/master.css'>";
   echo "<script src='js/jquery-1.11.1.min.js'></script>";

   echo "<div id=header style='font-size: 150%; background-color: grey; padding: 3px; font-weight: bold;'>PowerShell Automation</div>";
}

function displayNavigation() {
   echo "<a href='index.php'>HOME</a>";
   echo "<br />";
}

function processAction() {
   $action = $_REQUEST['action'];
   $server = $_REQUEST['server'];
   $username = $_SERVER['AUTH_USER'];
   $password = $_REQUEST['password'];
   
   switch ($action) {
      case 'runGet-ChildItem':
         runPowershellScript($server, $action, $username, $password);
         break;
   }
}

function runPowershellScript($server, $command, $username, $password) {
   $powershellCommand = "powershell -File c:\\inetpub\\wwwroot\\PowerShell\\runRemoteCommand.ps1 -server $server -username $username -password $password -command $command < NUL";
   
   $output = shell_exec($powershellCommand);
   echo "<h1>Output</h1>";
   echo $output;
}

function displayHome() {
   echo "<br />";
   echo "<form id=serverInput method=post>";
   echo "<table border=1 width=400>";
   
   echo "<tr><td width=120>Action <span class=required>*</span></td><td><input type=radio name=action id=Get-ChildItem value=runGet-ChildItem>Get-ChildItem<br /></td></tr>";
   echo "<tr><td>Server <span class=required>*</span></td><td><input type=radio name=server value=SERVER1>SERVER1<br/></td></tr>";
   echo "<tr><td>Password</td><td><input type=password id=password name=password size=40></td></tr>";
   echo "<tr><td colspan=2 align=center><input type=submit value=submit></tr>";
   echo "</table>";
   echo "</form>";
   echo "<div id=contentArea></div>";
}

##############
#MAIN SECTION
##############
displayHeader();
checkAuthorizedUsers();
displayNavigation();
displayHome();

if (isset($_REQUEST['action'])) {
   processAction();
}

?>